﻿using SqlSugar;
using System.Diagnostics;
using System.Reflection;

namespace QingZhouLinYe.HttpApi.Extensions
{
    public static class ServiceExtensions
    {
        //跨域中间件
        public static void AddCors_Domain(this IServiceCollection services)
        {
            services.AddCors(
                options =>
                {
                    options.AddPolicy(
                    "AnyPolicy",
                    builder => builder.AllowAnyOrigin()
                        //.With开头的是加以限制，开启白名单方式
                        //以下两条是不加限制，允许所有请求
                        .AllowAnyMethod()
                        .AllowAnyHeader());
                });
        }

        //Sqlsugar 中间件
        public static void AddCors_SqlSugar(this IServiceCollection services)
        {
            IConfiguration _config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();
            services.AddScoped(options =>
            {
                return new SqlSugarClient(new List<ConnectionConfig>()
                        {
                        new ConnectionConfig()
                        {
                        ConnectionString = _config.GetConnectionString("SqlSugarConn"),
                        DbType = DbType.SqlServer,
                        IsAutoCloseConnection = true
                        }
                        });
            });

        }

        /*
             1、SqlSugarClient 原生模式访问数据库(性能强)
             2、SqlSugarScope 单例模式访问数据库（使用更简单，性能也不错）
             决定用性能更强的SqlSugarClient
         */
        public static SqlSugarClient initDbContext(ConfigurationManager config, string? slaveConnStr)
        {
            SqlSugarClient dbClient = new SqlSugarClient(new ConnectionConfig()
            {
                //定义数据库类型
                DbType = DbType.SqlServer,
                ConnectionString = config.GetConnectionString(slaveConnStr),
                IsAutoCloseConnection = true,//自动关闭连接
                // 用于支持实体类中的 [SugarColumn] 特性
                InitKeyType = InitKeyType.Attribute,
               
                ConfigureExternalServices = new ConfigureExternalServices
                {
                    //注意:  这儿AOP设置不能少
                    EntityService = (c, p) =>
                    {
                        /***高版C#写法
                         * 支持string?和string，实体字段没有加?代表建表时该字段不能为null
                         * ***/
                        if (p.IsPrimarykey == false && new NullabilityInfoContext().Create(c).WriteState is NullabilityState.Nullable)
                        {
                            p.IsNullable = true;
                        }
                    }
                }
            }, dbClient =>
            {
                dbClient.Aop.OnLogExecuted = (sql, pars) =>
                {
                    //获取原生SQL推荐  性能OK
                    Debug.WriteLine(UtilMethods.GetNativeSql(sql, pars));   //VS2022输出窗口输出提示信息

                    //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                    //Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer, sql, pars));   //vs2022控制台窗口输出提示信息
                };
            });
            return dbClient;
        }

    }
}




